package com.edu.atams.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.edu.atams.common.lang.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @Author gfj
 * @Date 2021/10/4 16:07
 * @description 文件上下传
 */

@RestController
@RequestMapping("/files")
@Slf4j
public class FileController extends BaseController{
    @Value("${file.port}")
    private String httpPort;

    @Value("${server.port}")
    private String httpsPort;

    @Value("${file.ip}")
    private String ip;

    /**
     * 上传接口
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();  // 获取源文件的名称
        // 定义文件的唯一标识（前缀）
        String flag = IdUtil.fastSimpleUUID();
        String rootFilePath = System.getProperty("user.dir") + "/files/" + flag + "_" + originalFilename;  // 获取上传的路径
        FileUtil.writeBytes(file.getBytes(), rootFilePath);  // 把文件写入到上传的路径
        log.info("http图片已上传");
        return Result.succ("http://" + ip + ":" + httpPort + "/files/" + flag);  // 返回结果 url
    }

    /**
     * 微信上传接口
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/wx/upload")
    public Result wxUpload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();  // 获取源文件的名称
        // 定义文件的唯一标识（前缀）
        String flag = IdUtil.fastSimpleUUID();
        String rootFilePath = System.getProperty("user.dir") + "/files/" + flag + "_" + originalFilename;  // 获取上传的路径
        FileUtil.writeBytes(file.getBytes(), rootFilePath);  // 把文件写入到上传的路径
        log.info("https图片已上传");
        return Result.succ("https://" + ip + ":" + httpsPort + "/files/" + flag);  // 返回结果 url
    }

    /**
     * 需要設置editor編輯器指定返回格式，重寫
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/editorUploadFile")
    public Map<Object, Object> editorUploadFile(MultipartFile file, HttpServletRequest request) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String uuid = IdUtil.fastSimpleUUID();
        String rootFilePath = System.getProperty("user.dir") + "/files/" + uuid + "_" + originalFilename;
        FileUtil.writeBytes(file.getBytes(),rootFilePath);
//        String path = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/files/" + uuid + "_" + originalFilename;
        String path = request.getScheme() + "://" + ip + ":" + httpPort + "/files/" + uuid + "_" + originalFilename;
        JSONArray jsonArr = new JSONArray();
        jsonArr.add(new JSONObject().set("url",path));
        return MapUtil.builder()
                .put("errno",0)
                .put("data",jsonArr)
                .build();
    }

    /**
     * 下载接口
     * @param flag
     * @param response
     */
    @GetMapping("/{flag}")
    public void getFiles(@PathVariable String flag, HttpServletResponse response) {
        OutputStream os;  // 新建一个输出流对象
        String basePath = System.getProperty("user.dir") + "/files/";  // 定于文件上传的根路径
        List<String> fileNames = FileUtil.listFileNames(basePath);  // 获取所有的文件名称
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");  // 找到跟参数一致的文件
        try {
            if (StrUtil.isNotEmpty(fileName)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + fileName);  // 通过文件的路径读取文件字节流
                os = response.getOutputStream();   // 通过输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }



}
